<!DOCTYPE html>
<html lang=zh-CN>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="google-site-verification" content="xBT4GhYoi5qRD5tr338pgPM5OWHHIDR6mNg1a3euekI" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta property="og:description" content="samuel-24276的博客">
    <meta property="og:type" content="website">
    <meta name="description" content="samuel-24276的博客">
    <meta name="keyword"  content="aircloud">
    <link rel="shortcut icon" href="/myblog/img/favicon.ico">

    <title>
        
        正则表达式基础 - samuel-24276的博客 | samuel-24276&#39;s Blog
        
    </title>

    <!-- Custom CSS -->
    
<link rel="stylesheet" href="/myblog/css/aircloud.css">

    
<link rel="stylesheet" href="/myblog/css/gitment.css">

    <!--<link rel="stylesheet" href="https://imsun.github.io/gitment/style/default.css">-->
    <link href="//at.alicdn.com/t/font_620856_28hi1hpxx24.css" rel="stylesheet" type="text/css">
    <!-- ga & ba script hoook -->
    <script></script>
<meta name="generator" content="Hexo 7.1.1"></head>

<body>

<div class="site-nav-toggle" id="site-nav-toggle">
    <button>
        <span class="btn-bar"></span>
        <span class="btn-bar"></span>
        <span class="btn-bar"></span>
    </button>
</div>

<div class="index-about">
    <i> Like what you do, do what you like </i>
</div>

<div class="index-container">
    
    <div class="index-left">
        
<div class="nav" id="nav">
    <div class="avatar-name">
        <div class="avatar ">
            <img src="/myblog/img/avatar.jpg" />
        </div>
        <div class="name">
            <i>samuel-24276</i>
        </div>
    </div>
    <div class="contents" id="nav-content">
        <ul>
            <li >
                <a href="/myblog/">
                    <i class="iconfont icon-shouye1"></i>
                    <span>主页</span>
                </a>
            </li>
            <li >
                <a href="/myblog/tags">
                    <i class="iconfont icon-biaoqian1"></i>
                    <span>标签</span>
                </a>
            </li>
            <li >
                <a href="/myblog/archives">
                    <i class="iconfont icon-guidang2"></i>
                    <span>存档</span>
                </a>
            </li>
            <li >
                <a href="/myblog/collect/">
                    <i class="iconfont icon-shoucang1"></i>
                    <span>收藏</span>
                </a>
            </li>
            <li >
                <a href="/myblog/about/">
                    <i class="iconfont icon-guanyu2"></i>
                    <span>关于</span>
                </a>
            </li>
            
            <li>
                <a id="search">
                    <i class="iconfont icon-sousuo1"></i>
                    <span>搜索</span>
                </a>
            </li>
            
        </ul>
    </div>
    
        <div id="toc" class="toc-article">
    <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#1-re-match"><span class="toc-text">1.re.match()</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-1-%E5%B8%B8%E8%A7%84%E5%8C%B9%E9%85%8D"><span class="toc-text">1.1.常规匹配</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-2-%E6%B3%9B%E5%8C%B9%E9%85%8D"><span class="toc-text">1.2.泛匹配</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-3-%E5%8C%B9%E9%85%8D%E7%9B%AE%E6%A0%87"><span class="toc-text">1.3.匹配目标</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-4-%E8%B4%AA%E5%A9%AA%E5%8C%B9%E9%85%8D"><span class="toc-text">1.4.贪婪匹配</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-5-%E9%9D%9E%E8%B4%AA%E5%A9%AA%E6%A8%A1%E5%BC%8F"><span class="toc-text">1.5.非贪婪模式</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-6-%E5%8C%B9%E9%85%8D%E6%A8%A1%E5%BC%8F"><span class="toc-text">1.6.匹配模式</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-7-%E8%BD%AC%E4%B9%89%E5%AD%97%E7%AC%A6"><span class="toc-text">1.7.转义字符</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#2-re-search"><span class="toc-text">2.re.search()</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8C%B9%E9%85%8D%E6%BC%94%E7%BB%83"><span class="toc-text">匹配演练</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#3-re-findall"><span class="toc-text">3.re.findall()</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#4-re-sub"><span class="toc-text">4.re.sub()</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#5-re-compile"><span class="toc-text">5.re.compile()</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#6-%E5%AE%9E%E6%88%98%E7%BB%83%E4%B9%A0%E2%80%93%E7%88%AC%E5%8F%96%E6%9C%AC%E5%8D%9A%E5%AE%A2%E6%96%87%E7%AB%A0%E7%9A%84%E7%9B%AE%E5%BD%95"><span class="toc-text">6.实战练习–爬取本博客文章的目录</span></a></li></ol>
</div>
    
</div>


<div class="search-field" id="search-field">
    <div class="search-bg" id="search-bg"></div>
    <div class="search-container">
        <div class="search-input">
            <span id="esc-search"> <i class="icon-fanhui iconfont"></i></span>
            <input id="search-input"/>
            <span id="begin-search">搜索</span>
        </div>
        <div class="search-result-container" id="search-result-container">

        </div>
    </div>
</div>

        <div class="index-about-mobile">
            <i> Like what you do, do what you like </i>
        </div>
    </div>
    
    <div class="index-middle">
        <!-- Main Content -->
        


<div class="post-container">
    <div class="post-title">
        正则表达式基础
    </div>

    <div class="post-meta">
        <span class="attr">发布于：<span>2020-03-25 22:14:38</span></span>
        
        <span class="attr">标签：/
        
        <a class="tag" href="/myblog/tags/#工具" title="工具">工具</a>
        <span>/</span>
        
        <a class="tag" href="/myblog/tags/#Python" title="Python">Python</a>
        <span>/</span>
        
        
        </span>
        <span class="attr">访问：<span id="busuanzi_value_page_pv"></span>
</span>
</span>
    </div>
    <div class="post-content no-indent">
        <blockquote>
<p>正则表达式是对<strong>字符串操作的一种逻辑公式</strong>，就是用事先定义好的一些特定字符、及这些特定字符的组合，组成一个“规则字符串”，这个“规则字符串”用来表达对字符串的一种过滤逻辑</p>
</blockquote>
<blockquote>
<p>非Pytho独有，re模块实现</p>
</blockquote>
<p>打开<a target="_blank" rel="noopener" href="https://tool.oschina.net/regex" title="开源中国在线工具">开源中国在线工具</a> 进行正则表达式测试。</p>
<h1 id="1-re-match"><a href="#1-re-match" class="headerlink" title="1.re.match()"></a>1.re.match()</h1><p>re.match(pattern, string, flag&#x3D;0)<br>pattern为正则表达式，string为匹配字符串,flag为匹配模式<br>从第一个字符开始匹配，若第一个字符不匹配，则不能匹配</p>
<h2 id="1-1-常规匹配"><a href="#1-1-常规匹配" class="headerlink" title="1.1.常规匹配"></a>1.1.常规匹配</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> re</span><br><span class="line"></span><br><span class="line">content = <span class="string">&#x27;hello 1234567 world_This is a Regex Demo&#x27;</span></span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">len</span>(content))</span><br><span class="line">result = re.<span class="keyword">match</span>(<span class="string">&#x27;^hello\s\d\d\d\s\d&#123;4&#125;\s\w&#123;10&#125;.*Demo$&#x27;</span>,content)</span><br><span class="line"><span class="built_in">print</span>(result)</span><br><span class="line"><span class="built_in">print</span>(result.group())</span><br><span class="line"><span class="built_in">print</span>(result.span())</span><br></pre></td></tr></table></figure>
<p>len()返回字符串长度，match()返回匹配结果，group()返回字符串，span()返回匹配区间</p>
<h2 id="1-2-泛匹配"><a href="#1-2-泛匹配" class="headerlink" title="1.2.泛匹配"></a>1.2.泛匹配</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">result  = re.<span class="keyword">match</span>(<span class="string">&#x27;^hello.*Demo$&#x27;</span>, content)</span><br><span class="line"><span class="built_in">print</span>(result)</span><br><span class="line"><span class="built_in">print</span>(result.group())</span><br><span class="line"><span class="built_in">print</span>(result.span())</span><br></pre></td></tr></table></figure>

<h2 id="1-3-匹配目标"><a href="#1-3-匹配目标" class="headerlink" title="1.3.匹配目标"></a>1.3.匹配目标</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">result  = re.<span class="keyword">match</span>(<span class="string">&#x27;^hello\s(\d+)\s.*Demo$&#x27;</span>, content)</span><br><span class="line"><span class="built_in">print</span>(result)</span><br><span class="line"><span class="built_in">print</span>(result.group())</span><br><span class="line"><span class="built_in">print</span>(result.span())</span><br><span class="line"><span class="built_in">print</span>(result.group())</span><br></pre></td></tr></table></figure>

<p>要想获取匹配的数据，可以先用()括起来，然后指定其左右端点（这里是空格\s）,就可以通过group(n)来获取了</p>
<h2 id="1-4-贪婪匹配"><a href="#1-4-贪婪匹配" class="headerlink" title="1.4.贪婪匹配"></a>1.4.贪婪匹配</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">result = re.<span class="keyword">match</span>(<span class="string">&#x27;^he.*(\d+).*Demo$&#x27;</span>,content)</span><br><span class="line"><span class="built_in">print</span>(result)</span><br><span class="line"><span class="built_in">print</span>(result.group(<span class="number">1</span>))</span><br></pre></td></tr></table></figure>

<p>.*会匹配尽可能多的字符，只保留（）内容的一个字符</p>
<h2 id="1-5-非贪婪模式"><a href="#1-5-非贪婪模式" class="headerlink" title="1.5.非贪婪模式"></a>1.5.非贪婪模式</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">result = re.<span class="keyword">match</span>(<span class="string">&#x27;^he.*?(\d+).*Demo$&#x27;</span>,content)</span><br><span class="line"><span class="built_in">print</span>(result)</span><br><span class="line"><span class="built_in">print</span>(result.group(<span class="number">1</span>))</span><br></pre></td></tr></table></figure>
<p>?在这里使.*匹配尽可能少的字符，保留（）内容的全部字符，非常方便</p>
<h2 id="1-6-匹配模式"><a href="#1-6-匹配模式" class="headerlink" title="1.6.匹配模式"></a>1.6.匹配模式</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">content = <span class="string">&#x27;hello 1234567 world_This </span></span><br><span class="line"><span class="string">is a Regex Demo&#x27;</span></span><br><span class="line">result = re.<span class="keyword">match</span>(<span class="string">&#x27;^he.*?(\d+).*?Demo$&#x27;</span>,content,re.S)</span><br><span class="line"><span class="built_in">print</span>(result)</span><br><span class="line"><span class="built_in">print</span>(result.group(<span class="number">1</span>))</span><br></pre></td></tr></table></figure>
<p>.*是不能匹配换行符的，加上re.S参数后.就可以匹配换行符了</p>
<h2 id="1-7-转义字符"><a href="#1-7-转义字符" class="headerlink" title="1.7.转义字符"></a>1.7.转义字符</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> re</span><br><span class="line">content = <span class="string">&#x27;price is $5.00&#x27;</span></span><br><span class="line">result = re.<span class="keyword">match</span>(<span class="string">&#x27;price is $5.00&#x27;</span>, content)</span><br><span class="line"><span class="built_in">print</span>(result)</span><br></pre></td></tr></table></figure>

<p>显示None，无法匹配，应该在特殊字符前加\进行转义</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">result = re.<span class="keyword">match</span>(<span class="string">&#x27;price is \$5.00&#x27;</span>, content)</span><br><span class="line"><span class="built_in">print</span>(result)</span><br></pre></td></tr></table></figure>

<h1 id="2-re-search"><a href="#2-re-search" class="headerlink" title="2.re.search()"></a>2.re.search()</h1><p>扫描整个字符串，并返回第一个成功的匹配</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> re</span><br><span class="line"></span><br><span class="line">content = <span class="string">&#x27;Extra string hello 1234567 world_This is a Regex Demo&#x27;</span></span><br><span class="line">result = re.<span class="keyword">match</span>(<span class="string">&#x27;he.*?(\d+).*Demo$&#x27;</span>,content)</span><br><span class="line"><span class="built_in">print</span>(result)</span><br><span class="line">result = re.search(<span class="string">&#x27;he.*?(\d+).*Demo$&#x27;</span>,content)</span><br><span class="line"><span class="built_in">print</span>(result)</span><br><span class="line"><span class="built_in">print</span>(result.group())</span><br><span class="line"><span class="built_in">print</span>(result.span())</span><br></pre></td></tr></table></figure>

<p><strong>总结：为了匹配方便，能用search()就不用match()</strong></p>
<h2 id="匹配演练"><a href="#匹配演练" class="headerlink" title="匹配演练"></a>匹配演练</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> requests</span><br><span class="line"><span class="keyword">import</span> re</span><br><span class="line"></span><br><span class="line">res = requests.get(<span class="string">&#x27;http://baidu.com&#x27;</span>)</span><br><span class="line">text = res.text</span><br><span class="line"><span class="built_in">print</span>(text)</span><br><span class="line"></span><br><span class="line">result = re.search(<span class="string">&#x27;&lt;meta\shttp-equiv=&quot;(.*?)&quot;.*?&#x27;</span>, text, re.S)</span><br><span class="line"><span class="built_in">print</span>(result)</span><br><span class="line"><span class="keyword">if</span> result:</span><br><span class="line">	<span class="built_in">print</span>(result.group(<span class="number">1</span>))</span><br></pre></td></tr></table></figure>

<p>注意在命令行粘贴代码时，print(result.group(1))前的缩进被省略了，所以要手动加上</p>
<h1 id="3-re-findall"><a href="#3-re-findall" class="headerlink" title="3.re.findall()"></a>3.re.findall()</h1><p>搜索字符串，以列表形式返回全部能匹配的子串 </p>
<h1 id="4-re-sub"><a href="#4-re-sub" class="headerlink" title="4.re.sub()"></a>4.re.sub()</h1><p>替换字符串中每一个匹配的子串后返回替换后的字符串<br>参数列表（匹配子串， 替换字符串， 原字符串）</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> re</span><br><span class="line"></span><br><span class="line">content = <span class="string">&#x27;hello 1234567 world_This is a Regex Demo&#x27;</span></span><br><span class="line"><span class="built_in">print</span>(content)</span><br><span class="line">content = re.sub(<span class="string">&#x27;\d+&#x27;</span>, <span class="string">&#x27;&#x27;</span>, content)</span><br><span class="line"><span class="built_in">print</span>(content)</span><br></pre></td></tr></table></figure>

<p>用空字符替换数字，相当于删除</p>
<h1 id="5-re-compile"><a href="#5-re-compile" class="headerlink" title="5.re.compile()"></a>5.re.compile()</h1><p>把正则字符串编译成正则表达式对象，用于代码复用</p>
<h1 id="6-实战练习–爬取本博客文章的目录"><a href="#6-实战练习–爬取本博客文章的目录" class="headerlink" title="6.实战练习–爬取本博客文章的目录"></a>6.实战练习–爬取本博客文章的目录</h1><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> requests</span><br><span class="line"><span class="keyword">import</span> re</span><br><span class="line">res = requests.get(<span class="string">&#x27;https://samuel-winston.gitee.io/myblog/&#x27;</span>)</span><br><span class="line"><span class="built_in">print</span>(res.text)</span><br><span class="line"><span class="built_in">print</span>(res.encoding)</span><br><span class="line">res.encoding = <span class="string">&quot;utf-8&quot;</span></span><br><span class="line">pattern = re.<span class="built_in">compile</span>(<span class="string">&#x27;&lt;div.*?post-preview.*?href=&quot;(.*?)&quot;.*?&#x27;</span>, re.S)</span><br><span class="line">results = re.findall(pattern, res.text)</span><br><span class="line"><span class="built_in">print</span>(results)</span><br><span class="line"><span class="keyword">for</span> result <span class="keyword">in</span> results:	</span><br><span class="line">	<span class="built_in">print</span>(result)</span><br></pre></td></tr></table></figure>

<hr>

        
            <div class="donate-container">
    <div class="donate-button">
        <button id="donate-button">赞赏</button>
    </div>
    <div class="donate-img-container hide" id="donate-img-container">
        <img id="donate-img" src="" data-src="/myblog/img/donate.jpg">
        <p> 感谢鼓励 </p>
    </div>
</div>
        
        <br />
        <div id="comment-container">
        </div>
        <div id="disqus_thread"></div>
        <div id="lv-container"></div>
        <div class="giscus"></div>
    </div>
</div>

    </div>
</div>


<footer class="footer">
    <ul class="list-inline text-center">
        
        

        

        

        
        <li>
            <a target="_blank"  href="https://github.com/samuel-24276">
                            <span class="fa-stack fa-lg">
                                <i class="iconfont icon-github"></i>
                            </span>
            </a>
        </li>
        

        

    </ul>
    
    <p>
        <span>/</span>
        
        <span><a target="_blank" rel="noopener" href="https://github.com/samuel-24276">samuel-24276&#39;s Page</a></span>
        <span>/</span>
        
        <span><a target="_blank" rel="noopener" href="https://beian.miit.gov.cn/">北京-未备案</a></span>
        <span>/</span>
        
        <span><a href="#">返回顶部</a></span>
        <span>/</span>
        
    </p>
    
    <p>
        <span id="busuanzi_container_site_pv">
            <span id="busuanzi_value_site_pv"></span>PV
        </span>
        <span id="busuanzi_container_site_uv">
            <span id="busuanzi_value_site_uv"></span>UV
        </span>
        Created By <a target="_blank" rel="noopener" href="https://hexo.io/">Hexo</a>  Theme <a target="_blank" rel="noopener" href="https://github.com/aircloud/hexo-theme-aircloud">AirCloud</a></p>
</footer>




</body>

<script>
    // We expose some of the variables needed by the front end
    window.hexo_search_path = "search.json"
    window.hexo_root = "/myblog/"
    window.isPost = true
</script>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>

<script src="/myblog/js/index.js"></script>

<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>






    <script type="text/javascript">
       (function() {
           if (typeof LivereTower === 'function') { return; }

           var j, d = document.getElementById('lv-container');

           d.setAttribute('data-id','city');
           d.setAttribute('data-uid' , 'MTAyMC80OTA5OC8yNTU5Mw==');

           j = document.createElement('script');
           j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
           j.async = true;

           d.appendChild(j);
       })();
    </script>
    <noscript>为正常使用来必力评论功能请激活JavaScript</noscript>
    </div>

</html>
